<template>
  <div class="claim-container">
    <div class="toolbar">
      <div class="text-btn pointer" @click="handle_calculate">计算</div>
      <div class="text-btn pointer" v-print="'#claim-table-print'">打印</div>
      <div class="text-btn pointer" @click="handle_export">导出</div>
      <div class="text-btn pointer" @click="showDialog('compareDialog', queryParams.year)">方案对比</div>

      <div class="programme">
        <el-switch v-model="programme" />
        <span style="margin: 0 10px">展示方案</span>
        <transition name="fade-transform">
          <div v-show="programme">
            <el-select v-model="editingForm.logId" @change="handle_select_programme" size="mini" style="width: 160px">
              <span slot="prefix" class="select-slot"><span></span></span>
              <el-option label="新方案" :value="null"></el-option>
              <el-option v-for="item in programmeOptions" :key="item.logId" :label="item.logName" :value="item.logId"></el-option>
            </el-select>
            <i class="el-icon-folder-delete pointer" @click="handle_delete"><span class="icon-text">删除</span></i>
            <i class="el-icon-edit pointer" @click="handleEditStatus"><span class="icon-text">编辑</span></i>           
          </div>
        </transition>
      </div>

      <i class="el-icon-document pointer" @click="showDialog('saveDialog', editingForm)"><span class="icon-text">保存</span></i>
      <i class="el-icon-setting pointer" @click="showDialog('manageDialog', queryParams.year)"><span class="icon-text">方案管理</span></i>
      <i class="el-icon-s-promotion pointer" @click="handle_finalization"><span class="icon-text">定稿提交</span></i>

    </div>
    <div class="content">
      <el-form :model="queryParams" inline>
        <el-form-item prop="year" label="年度" size="mini">
          <el-date-picker
            v-model="queryParams.year"
            type="year"
            value-format="yyyy"
            placeholder="选择年份"
            :clearable="false"
            @change="handle_search"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item size="mini">
          <el-button type="primary" @click="handle_search">查询</el-button>
        </el-form-item>
      </el-form>

      <div class="content-table" id="claim-table-print">
        <!-- 收入认领 -->
        <div class="left">
          <div class="title">收入认领</div>
          <div class="tableBox" style="margin-top: 20px;">
            <el-table
              v-loading="loading"
              :data="claimsTableData"
              style="width: 100%"
              border
              :cell-style="cellStyle"
              :header-cell-style="{color:'#000', padding: '0', 'font-size': '12px', 'font-weight': '500', height: '40px'}"
            >
              <el-table-column label="" prop="title" align="center"></el-table-column>
              <el-table-column label="码号收入" prop="mh" align="center">
                <template slot-scope="{ row, $index }">
                  <el-input v-if="$index <= 1 && isEditing" v-model="row.mh" :disabled="areaId == 1" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g,'$1')" size="mini" >
                    <span slot="suffix" v-if="$index == 1">%</span>
                  </el-input>
                  <span v-else-if="$index>=5">{{row.mh != null ? row.mh + '%' : ''}}</span>
                  <span v-else>{{row.mh}}</span>
                </template>
              </el-table-column>
              <el-table-column label="产数收入" prop="cs" align="center">
                <template slot-scope="{ row, $index }">
                  <el-input v-if="$index <= 1 && isEditing" v-model="row.cs" :disabled="areaId == 1" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g,'$1')" size="mini">
                    <span slot="suffix" v-if="$index == 1">%</span>
                  </el-input>
                  <span v-else-if="$index>=5">{{row.cs != null ? row.cs + '%' : ''}}</span>
                  <span v-else>{{row.cs}}</span>
                </template>
              </el-table-column>
              <el-table-column label="非码号非产数收入" prop="js" align="center" min-width="90">
                <template slot-scope="{ row, $index }">
                  <el-input v-if="$index == 2 && isEditing" v-model="row.js" :disabled="areaId == 1" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g,'$1')" size="mini" ></el-input>
                  <span v-else-if="$index>=5">{{row.js != null ? row.js + '%' : ''}}</span>
                  <span v-else>{{row.js}}</span>
                </template>
              </el-table-column>
              <el-table-column label="主营合计" prop="zy" align="center">
                <template slot-scope="{ row, $index }">
                  <el-input v-if="$index == 0 && isEditing" v-model="row.zy" :disabled="areaId == 1" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g,'$1')" size="mini"></el-input>
                  <span v-else-if="$index>=5">{{row.zy != null ? row.zy + '%' : ''}}</span>
                  <span v-else>{{row.zy}}</span>
                </template>
              </el-table-column>
            </el-table>            
          </div>

        </div>
        <!-- 资源配置 -->
        <div class="right">
          <div class="title">资源配置</div>
          <el-descriptions :column="2" size="small" border style="margin-top: 20px" v-loading="loading">
            <el-descriptions-item v-for="item in resourceColumn" :key="item.prop">
              <template slot="label">
                <div style="text-align: center">{{item.label}}</div>
              </template>
              <div style="padding: 0 8px">
                <el-input v-model="resourceData[item.prop]" v-if="item.input && isEditing" :disabled="areaId == 1" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,4})?).*$/g,'$1')" size="mini" >
                  <span slot="suffix" v-if="item.suffix">%</span>
                </el-input>
                <span v-else-if="item.suffix">{{resourceData[item.prop] != null ? resourceData[item.prop] + '%' : ''}}</span>
                <span v-else>{{resourceData[item.prop]}}</span>
              </div>
            </el-descriptions-item>
          </el-descriptions>
        </div>        
      </div>

      <div class="rule-text">
        <div class="left">
          <p>收入认领规则：</p>
          <ul>
            <li>主营=码号+产数+非码号非产数</li>
            <li>主营认领R0/R2时，码号需大于等于码号R0、产数需大于等于产数R0；</li>
            <li>主营认领R3/R4时，码号需大于等于码号R2；</li>
            <li>其他收入（非码号非产数），只能在既定的T值上“只减不增”。</li>
          </ul>
        </div>
        <div class="right">
          <p>资源配置规则：</p>
          <ul>
            <li>主营收入基数=ICT收入基数+基本面收入基数；</li>
            <li>ICT存量收入取自协议级系统相关数据；</li>
            <li>ICT配置率：参考各单位近3年的账面ICT收入及成本情况；</li>
            <li>主营增量收入增配规则：按照“基数-R0”、“R0-R2”、“R2-R3”、“R3-R4”、“R4以上”分段配置90%、95%、100%、105%和110%的增量成本。</li>
          </ul>
        </div>
      </div>
    </div>
    
    <CompareDialog ref="compareDialog" />
    <SaveDialog ref="saveDialog" @save="handle_save" />
    <ManageDialog ref="manageDialog" @edit="handle_edit" />

  </div>
</template>
<script>
import { getSessionStorage } from '@/common/js/storage'
import { $budgetAPI } from "@/api";
import { getCookie } from "@/common/js/cookie";
import { claimsTableData, resourceData, resourceColumn } from "./tableData.js"
import { downLoadExcelBody } from "@/utils/zipdownload.js";

export default {
  components: {
    CompareDialog: () => import("./components/compareDialog.vue"),
    SaveDialog: () => import("./components/saveDialog.vue"),
    ManageDialog: () => import("./components/manageDialog.vue"),
  },
  data(){
    return {
      programme: false,
      // programmeVal: null, //保证可以监听到输入框修改
      programmeOptions: [],
      queryParams: {
        year: this.moment().format("YYYY"),
        // year: "2023",
      },
      loading: false,
      claimsTableData: JSON.parse(JSON.stringify(claimsTableData)),
      resourceData : { ...resourceData },
      resourceColumn,
      isCalc: false, //是否计算过
      isChanged: false, //是否修改过
      isEditing: true, //是否可编辑
      //编辑中方案数据
      editingForm: {
        logId: null,
        year: null,
        logName: null,
        flag: "0", //0未提交，1已提交
      },
      //修改前的数据
      beforeChangedData: {
        mh1: '',
        mh2: '',
        cs1: '',
        cs2: '',
        js: '',
        zy: '',
        ict_base_amt: '',
        profit_base_amt: '',
        jbm_profit_rate: '',
        improve_rate: '',
        ict_cl_income: '',
        ict_allocate_rate: ''
      },

      areaId: JSON.parse(getSessionStorage('accountInfo')).areaId
    }
  },
  watch: {
    claimsTableData: {
      deep: true,
      handler(val){
        if(this.editingForm.logId === null) return;
        this.isChanged = this.checkIsChanged();
        console.log(this.isChanged);
      }
    },
    resourceData: {
      deep: true,
      handler(val){
        if(this.editingForm.logId === null) return;
        this.isChanged = this.checkIsChanged();
        console.log(this.isChanged);
      }
    },
  },
  created(){
    this.getData();
  },
  methods: {
    getData(){
      this.loading = true;
      this.isEditing = true;
      this.claimsTableData = JSON.parse(JSON.stringify(claimsTableData));
      this.resourceData = {...resourceData};
      $budgetAPI.claimSelect(
        {...this.queryParams, token: getCookie("token")}, 
        res => {
          this.alertError(res);
          if(res.code == 0){
            this.isCalc = false;
            this.isChanged = false;
            const { content } = res;
            if(content === null){
            } else {
              this.claimsTableData[0].js = content.T1;
              this.claimsTableData[5].mh = content.mhR0;
              this.claimsTableData[5].cs = content.csR0;
              this.claimsTableData[5].zy = content.zyR0;
              this.claimsTableData[6].mh = content.mhR2;
              this.claimsTableData[6].cs = content.csR2;
              this.claimsTableData[6].zy = content.zyR2;
              this.claimsTableData[7].zy = content.zyR3;
              this.claimsTableData[8].zy = content.zyR4;
            }
            this.getProgrammeList();
            this.editingForm.logId = null;
          }
          this.loading = false;
        },
        err => {
          this.alertError(err);
          this.loading = false
        }
      )
    },
    handle_search(){
      this.editingForm.logId = null;
      this.getData();
    },
    //获取方案列表
    getProgrammeList(){
      $budgetAPI.claimQueryPlan({
        year: this.queryParams.year,
        token: getCookie("token")
      },
      res =>{
        this.alertError(res);
        if(res.code == 0){
          this.programmeOptions = res.content;
          this.editingForm.logId = null;
        }
      },
      err => {
        this.alertError(err);
      })
    },
    //计算
    handle_calculate(){
      if(this.areaId == 1) return this.$message.warning("分公司人员认领");
      //非编辑状态
      if(!this.isEditing)
        return this.$message.warning("查看状态无法计算");
      //未填完整
      if(!this.checkCalcInput())
        return this.$message.warning("请填写全部输入框内容");
      this.loading = true;
      const { claim, resource } = this.handle_data();
      $budgetAPI.claimCalculation({
        token: getCookie("token"),
        claim,
        resource
      },
      res => {
        this.alertError(res);
        const { content } = res;
        if(res.code == 0){
          this.isCalc = true;
          this.resourceData = { ...content.resource };
          content.claim.forEach((it, i) => {
            this.claimsTableData[i].mh = it.mh;
            this.claimsTableData[i].cs = it.cs;
            this.claimsTableData[i].js = it.js;
            this.claimsTableData[i].zy = it.zy;
          });
          // this.assignBeforeChanged();
        }
        this.loading = false;
      },
      err => {
        this.loading = false;
        this.alertError(err);
      })
    },
    //保存
    handle_save(form){
      if(this.editingForm.logId !== null){
        this.handle_update(form);
        return;
      }
      const { claim, resource } = this.handle_data();
      $budgetAPI.claimSave({
        token: getCookie("token"),
        claim,
        resource,
        ...form
      },
      res => {
        this.alertError(res);
        if(res.code == 0){
          this.$refs.saveDialog.handle_close();
          this.$message.success("保存方案成功");
          this.getProgrammeList();
        }
      },
      err => {
        this.alertError(err);
      });
    },
    //更新
    handle_update(form){
      const { claim, resource } = this.handle_data();
      $budgetAPI.claimUpdatePlan(
      { ...form, claim, resource, token: getCookie("token") }, 
      res => {
        this.alertError(res);
        if(res.code == 0){
          this.$refs.saveDialog.handle_close();
          this.$message.success("更新方案成功");
          this.isCalc = false;
          this.isChanged = false;
          this.assignBeforeChanged();
        }
      },
      err => {
        this.alertError(err);
      }
      );
    },
    //删除
    async handle_delete(){
      if(this.editingForm.logId === null) return this.$message.warning("请先选择方案");
      if(this.editingForm.flag == 1) return this.$message.warning("已提交的方案无法删除");
      await this.$confirm('确认删除该条方案吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      $budgetAPI.claimDeletePlan({
        token: getCookie("token"),
        logId: this.editingForm.logId 
      }, 
      res => {
        this.alertError(res);
        if(res.code == 0){
          this.editingForm.logId = null;
          this.getProgrammeList();
          this.$message.success("删除方案成功");
        }
      },
      err => {
        this.alertError(err);
      })
    },
    //修改编辑状态
    handleEditStatus(){
      if(this.editingForm.flag == 1) return this.$message.warning("已提交的方案无法编辑");
      this.isEditing = true;
    },
    //查看编辑
    handle_edit(row){
      this.loading = true;
      $budgetAPI.claimQueryPlanList({
        token: getCookie("token"),
        logId1: row.logId,
      },
      res => {
        this.alertError(res);
        if(res.code == 0){
          const { claim, claimKey, resourceKey, resources } = res.content;
          this.claimsTableData = claimKey.map((it,i) => {
            return {
              title: this.claimsTableData[i].title,
              mh: claim[1][it] !== undefined ? claim[1][it] : '',
              cs: claim[2][it] !== undefined ? claim[2][it]: '',
              js: claim[3][it] !== undefined ? claim[3][it]: '',
              zy: claim[0][it] !== undefined ? claim[0][it]: ''
            }
          })
          let obj = {};
          resourceKey.forEach(it => {
            obj[it] = resources[0][it] !== undefined ? resources[0][it] : '';
          })
          this.resourceData = obj;

          this.isCalc = false;
          this.isChanged = false;
          
          this.isEditing = row.flag == "0";
          this.editingForm.logId = row.logId;
          this.editingForm.year = row.year;
          this.editingForm.logName = row.logName;

          this.assignBeforeChanged();
          this.$refs.manageDialog.handle_close();
        }
        this.loading = false;
      }, 
      err => {
        this.loading = false;
        this.alertError(err);
      })
    },
    //定稿提交
    async handle_finalization(){
      if(!this.isEditing) 
        return this.$message.warning("该方案已提交");
      if(this.editingForm.logId === null) 
        return this.$message.warning("请先选择方案");
      if(this.isChanged && !this.isCalc)
        return this.$message.warning("请先进行计算");
      
      await this.$confirm('是否确认提交？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
      $budgetAPI.claimFinalization(
        { token: getCookie("token"), logId: this.editingForm.logId, year: this.editingForm.year },
        res => {
          this.alertError(res);
          if(res.code == 0){
            this.$message.success("提交成功");
            this.isEditing = false;
          }
        },
        err => {
          this.alertError(err);
        }
      )
    },
    //导出
    handle_export(){
      const { claim, resource } = this.handle_data();
      downLoadExcelBody(
        "/budgetClaim/exportClaim", 
        { claim, resource, token: getCookie("token") },
        "收入认领"
        )
    },
    //选择方案
    handle_select_programme(val){
      if(val === null){
        this.getData();
      } else {
        let obj = this.programmeOptions.find(it => it.logId === val);
        this.handle_edit(obj);
      }
    },
    //处理提交的数据claim、resource
    handle_data(){
      let claim = this.claimsTableData.map(it => {
        return {
          mh: (it.mh !== '' && it.mh !== null) ? it.mh : null,
          cs: (it.cs !== '' && it.cs !== null) ? it.cs : null,
          js: (it.js !== '' && it.js !== null) ? it.js : null,
          zy: (it.zy !== '' && it.zy !== null) ? it.zy : null,
        }
      });
      let resource = {};
      for(let it in this.resourceData){
        if(this.resourceData[it] !== '' && this.resourceData[it] !== null){
          resource[it] = Number(this.resourceData[it]);
        }
      }
      return {
        claim,
        resource
      }
    },
    //弹窗
    showDialog(refName, val){
      if(refName === 'saveDialog'){
        //非编辑状态
        if(!this.isEditing) 
          return this.$message.warning("查看状态无法保存");

        //编辑后未修改
        if(this.editingForm.logId !== null && !this.isChanged) 
          return this.$message.warning("未进行修改");
        
        //未计算
        if(!this.isCalc)
          return this.$message.warning("请先进行计算");

        //未通过校验
        const { mh, cs, js, zy } = this.claimsTableData[4];
        if(mh !== "OK" || cs !== "OK" || js !== "OK" || zy !== "OK")
          return this.$message.warning("校验未通过，请重新计算");

        this.isChanged = true;
      }
      this.$refs[refName].init(val);
    },
    //检查计算框是否全不为空
    checkCalcInput(){
      const { claimsTableData, resourceData } = this;
      if(
        claimsTableData[0].mh !== '' &&
        claimsTableData[0].cs !== '' &&
        claimsTableData[0].zy !== '' &&
        claimsTableData[1].mh !== '' &&
        claimsTableData[1].cs !== '' &&
        claimsTableData[2].js !== '' &&
        resourceData.ict_base_amt !== '' &&
        resourceData.profit_base_amt !== '' &&
        resourceData.jbm_profit_rate !== '' &&
        resourceData.improve_rate !== '' &&
        resourceData.ict_cl_income !== '' &&
        resourceData.ict_allocate_rate !== ''
      ) return true;

      return false
    },
    //清空计算框
    clearCalcInput(){
      const { claimsTableData, resourceData } = this;
      claimsTableData[0].mh = '';
      claimsTableData[0].cs = '';
      claimsTableData[0].zy = '';
      claimsTableData[1].mh = '';
      claimsTableData[1].cs = '';
      claimsTableData[2].js = '';
      resourceData.ict_base_amt = '';
      resourceData.profit_base_amt = '';
      resourceData.jbm_profit_rate = '';
      resourceData.improve_rate = '';
      resourceData.ict_cl_income = '';
      resourceData.ict_allocate_rate = '';
    },
    //修改前数据赋值
    assignBeforeChanged(){
      const { ict_base_amt, profit_base_amt, jbm_profit_rate, 
              improve_rate, ict_cl_income, ict_allocate_rate } = this.resourceData,
            { claimsTableData } = this;

      this.beforeChangedData = {
        mh1: claimsTableData[0].mh,
        mh2: claimsTableData[1].mh,
        cs1: claimsTableData[0].cs,
        cs2: claimsTableData[1].cs,
        js: claimsTableData[2].js,
        zy: claimsTableData[0].zy,
        ict_base_amt,
        profit_base_amt,
        jbm_profit_rate,
        improve_rate,
        ict_cl_income,
        ict_allocate_rate,
      }
    },
    //判断计算框是否修改过数据
    checkIsChanged(){
      const { mh1, mh2, cs1, cs2, js, zy, ict_base_amt, profit_base_amt,
              jbm_profit_rate,improve_rate, ict_cl_income, ict_allocate_rate, 
            } = this.beforeChangedData,
            {claimsTableData, resourceData} = this;
            
      if(
        claimsTableData[0].mh == mh1 &&
        claimsTableData[1].mh == mh2 &&
        claimsTableData[0].cs == cs1 &&
        claimsTableData[1].cs == cs2 &&
        claimsTableData[2].js == js &&
        claimsTableData[0].zy == zy &&
        resourceData.ict_base_amt == ict_base_amt &&
        resourceData.profit_base_amt == profit_base_amt &&
        resourceData.jbm_profit_rate == jbm_profit_rate &&
        resourceData.improve_rate == improve_rate &&
        resourceData.ict_cl_income == ict_cl_income &&
        resourceData.ict_allocate_rate == ict_allocate_rate
      ) return false;
      return true;
    },
    cellStyle({ rowIndex, columnIndex }){
      if(rowIndex == 4){ 
        return {
          backgroundColor: "#FFB1B1"
        } 
      }
    }
  },
}
</script>
<style lang="scss" scoped>
  .claim-container {
    width: 99%;
    margin: 0 auto;
    border: 1px solid rgb(219, 219, 219);
    .toolbar {
      width: 100%;
      height: 48px;
      background-color: rgb(211,229,251);
      display: flex;
      align-items: center;
      font-size: 14px;
      padding: 0 10px;
      i {
        font-size: 20px;
        display: flex;
        align-items: center;
        margin: 0 10px;
      }
      .icon-text {
        font-size: 14px !important;
        margin-left: 2px;
      }
      .pointer {
        cursor: pointer;
        user-select: none;
        transition: color .2s;
        &:hover {
          color: blue;
        }
      }
      .text-btn {
        padding: 2px 15px;
        border-right: 1px solid rgb(142, 192, 253);
      }
      .programme {
        display: flex;
        flex: 1;
        align-items: center; 
        margin-left: 30px;
        > div {
          display: flex;
          align-items: center;          
        }
      }
      /deep/ .el-input--prefix .el-input__inner {
        padding-left: 20px;
      }
    }
    .content {
      padding: 20px;
      .content-table {
        display: flex;
        justify-content: space-between;
        .left, .right {
          width: 49%;
          .title {
            width: 100%;
            height: 40px;
            border-top: 1px solid rgb(56,150,242);
            border-bottom: 1px solid rgb(56,150,242);
            font-size: 18px;
            font-weight: 600;
            line-height: 36px;
            padding-left: 10px;
          }
        }
        /deep/ .el-input {
          input {
            color: #000 !important;
            background-color: #FFB1B1 !important;
          }
          .el-input__suffix {
            color: #000 !important;
          }
        }
      }
      .rule-text {
        color: rgb(145, 145, 145);
        font-size: 14px;
        font-weight: 400;
        margin-top: 20px;
        display: flex;
        justify-content: space-between;
        .left, .right {
          width: 49%;
        }
        ul {
          padding-left: 35px;
          li {
            list-style: disc !important;
          }
        }
      }
    }
  }
  /deep/ .el-form-item__label {
		font-size: 13px;
		padding-right: 10px;
		line-height: 32px !important;
	}
  /deep/ .el-table {
    .el-table__row {
      td {
        height: 40px !important;
        padding: 0 !important;
      }
      .cell {
        font-size: 13px !important;
        .el-input {
          .el-input__suffix {
            line-height: 28px !important;
          }
        }
      }
    }
    .el-input__suffix {
      line-height: 26px !important;
    }
  }
  /deep/ .el-descriptions .el-descriptions-row {
    .el-descriptions-item__cell {
      height: 40px !important;
      padding: 0 !important;
      text-align: center;
      color: #000;
      &:nth-child(1){
        width: 135px;
        background-color: rgb(211,229,251) !important;
      }
      &:nth-child(2){
        min-width: 140px;
        width: 23%;
      }
      &:nth-child(3){
        width: 185px;
        background-color: rgb(211,229,251) !important;
      }
      &:nth-child(4){
        min-width: 130px;
        width: 23%;
      }
    }
    .el-input__suffix {
      line-height: 26px !important;
    }
  }
  .select-slot {
    display: inline-block;
    margin-top: 9.5px;
    width: 10px;
    height: 10px;
    border-radius: 100%;
    background-color: rgb(0,160,255);
    text-align: center;
    line-height: 4px;
    > span {
      display: inline-block;
      width: 4px;
      height: 4px;
      border-radius: 100%;
      background-color: #fff;
    }
  }
  .fade-transform-leave-active {
    transition: all 0.1s;
    // animation: fade .2s reverse;
  }
  .fade-transform-enter-active {
    transition: all 0.1s;
    // animation: fade .2s;
  }

  .fade-transform-enter {
    opacity: 0;
    transform: translateX(-100%);
    // animation: fade;
  }

  .fade-transform-leave-to {
    opacity: 0;
    transform: translateX(-100%);
    // animation: fade reverse;
  }
  // @keyframes fade{
  //   0% {
  //     // opacity: 1;
  //     transform: translateX(0);
  //   }
  //   100% {
  //     // opacity: 0;
  //     transform: translateX(-100%);
  //   }
  // }
</style>